package com.zhfi.dataapply.service.impl;

import com.zhfi.dataapply.entity.TzResponse;
import com.zhfi.dataapply.service.ForwardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Map;

@Service
public class ForwardServiceImpl implements ForwardService {

    @Value("${token}")
    private String token;

    @Autowired
    private WebClient webClient;

    @Override
    public TzResponse requestForwarder(String url, Map<String, Object> params) {
        Mono<TzResponse> responseMono = webClient.get()
                .uri(getUri(url, params))
                .header("Authorization", token)
                .retrieve()
                .bodyToMono(TzResponse.class);
        TzResponse tzResponse = responseMono.block();
        System.out.println("-------------------------");
        System.out.println("请求路径" + url);
        System.out.println("请求参数" + params);
        System.out.println(tzResponse);
        if ("004".equals(tzResponse.getResCode())) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return requestForwarder(url, params);
        }
        return tzResponse;
    }

    private String getUri(String url, Map<String, Object> params){
        StringBuilder uriBuilder = new StringBuilder(256);
        uriBuilder.append("https://").append(url).append("?");
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            uriBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        return uriBuilder.toString();
    }

}
